/*
 * rule.cpp
 *
 *  Created on: 15/11/2012
 *      Author: cvan680
 */


#include "rule.h"
#include <algorithm>

namespace voreen {

Rule::Rule(){}

Rule::Rule(string rule){
	// reduce all tabs, newlines, whitespaces to one space
	rule_ = rule;

	std::vector<string> two_parts = tokenize(rule_, "->");

	if(two_parts.size() > 0){ std::cout << "\nfirst: [" << two_parts.at(0) << "]"; }
	if(two_parts.size() > 1){ std::cout << "\nsecond: [" << two_parts.at(1) << "]"; }


	if(two_parts.size() > 1){
		std::vector<string> first = tokenize(two_parts.at(0), ":");
		std::vector<string> second = tokenize(two_parts.at(1), ":");

		predecessor_ = NodeList(first.at(0));
		successor_ = NodeList(second.at(0));
		condition_ = "NOCOND";
		probability_ = 1.0;
	}

	// TODO make these into predecessor and successor nodelists.. make sure NodeList works and subsequently TechniqueWrapper


}

bool Rule::fires(NodeList state){
	return state.contains(predecessor_);
}

NodeList Rule::getPredecessor(){ return predecessor_; }
NodeList Rule::getSuccessor(){ return successor_; }

string Rule::cleanup(string rule){
	/*
	for(int i=0; i<rule.length(); ++i){
		if(rule[i] == "\n"){
			rule[i] = " ";
		}
		std::cout << "bla";
	}*/
	return rule;
}

std::vector<string> Rule::tokenize(string contents, string delimiter){
	std::vector<string> temps;
	string tmp;

	while(contents.length() > 0){
		int i = contents.find( delimiter );

		if(i >= 0 && i < contents.length()){
			tmp = contents.substr(0, i);
			tmp = trimmer(tmp);
			temps.push_back(tmp);
			contents.erase(0, i+delimiter.size()); // also remove delimiter
		}else{
			contents = trimmer(contents);
			temps.push_back(contents);
			contents = "";
		}
	}

	return temps;
}

string Rule::trimmer(string s){
	// trim trailing spaces
	size_t endpos = s.find_last_not_of(" \t");
	if( string::npos != endpos ){ s = s.substr( 0, endpos+1 ); }
	size_t startpos = s.find_first_not_of(" \t");
	if( string::npos != startpos ){ s = s.substr( startpos ); }
	return s;
}

void Rule::printString(){
	std::cout << "\nrule: " << rule_;
}

void Rule::print(){
	std::cout << "\nrule: ";
	predecessor_.printMe();
	std::cout << " -> ";
	successor_.printMe();
}


}
